<?php
namespace Admin\Controller;


class CategoryController extends CommonController
{
    private $category;

    public function __construct()
    {
        parent:: __construct();
        $this->category = M('category');
    }

    public function index()
    {
        $count = $this->category->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,2);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
//        dump($show);


        $categories = $this->category->where('parent_id=0')->order('sort_order')->limit($Page->firstRow.','.$Page->listRows)->select();
//        dump($this->category->getLastSql());
        foreach ($categories as $key => $vlaue){
            $id = $vlaue['id'];
            $categories[$key]['children'] = $this->category->where("parent_id='$id'")->select();
        }
        dump($categories);
        $this->assign('categories', $categories);
        $this->display();
    }

    public function store()
    {
        $category = D('Category');
        if (!$category->create()) {
            $this->error($category->getError());
        } else {
            $category->add();
            $this->success('新增栏目成功',U('index'));
        }
    }

    public function create()
    {
        $categories = $this->category->where('parent_id=0')->order('sort_order')->select();
        foreach ($categories as $key => $vlaue){
            $id = $vlaue['id'];
            $categories[$key]['children'] = $this->category->where("parent_id='$id'")->select();
        }
        $this->assign('categories', $categories);
        $this->display();
    }

    public function destory()
    {
        $id = I('get.id');
        $this->category->delete($id);
        $this->success('删除成功');
    }

    public function sort_order(){
        $ids = I('post.id');
        $sort_orders = I('post.sort_order');
        foreach ($ids as $key=>$value){
            $this->category->where("id='$value'")->setFeild('sort_order',$sort_orders[$key]);
        }
        $this->redirect('index');
    }

}